////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 Kentaro Sekimoto  All rights reserved.
////////////////////////////////////////////////////////////////////////////

#include <tinyhal.h>

extern volatile unsigned int* spisw_rs;
extern volatile unsigned int* spisw_di;
extern volatile unsigned int* spisw_ck;
extern volatile unsigned int* spisw_cs;
void SPISW_GPIO_Initialize(void);

#define MOSI    (*spisw_di)
#define CS_LOW  (*spisw_cs = 0)
#define CS_HIGH (*spisw_cs = 1)
#define CK_LOW  (*spisw_ck = 0)
#define CK_HIGH (*spisw_ck = 1)
#define DI_LOW  (*spisw_di = 0)
#define DI_HIGH (*spisw_di = 1)
#define RS_LOW  (*spisw_rs = 0)
#define RS_HIGH (*spisw_rs = 1)

void SPISW_Initialize(void)
{
    SPISW_GPIO_Initialize();
    CS_LOW;
    DI_LOW;
    CK_HIGH;
}

void SPISW_Reset(UINT32 v)
{
    if (v) {
        RS_HIGH;
    } else {
        RS_LOW;
    }
}

void SPISW_Write(UINT8 dat)
{
    UINT8 i = 8;
    while (i-- > 0) {
        MOSI = (dat & 0x80) ? 1 : 0;
        CK_LOW;
        CK_HIGH;
        dat <<= 1;
    }
}

void SPISW_LCD_cmd(UINT8 dat)
{
    // Enter command mode: SDATA=LOW at rising edge of 1st SCLK
    CS_LOW;
    DI_LOW;
    //CK_LOW; CK_LOW; CK_HIGH; CK_HIGH;
    CK_LOW; CK_HIGH;
    SPISW_Write(dat);
    CS_HIGH;
}
void SPISW_LCD_dat(UINT8 dat)
{
    // Enter data mode: SDATA=HIGH at rising edge of 1st SCLK
    CS_LOW;
    DI_HIGH;
    //CK_LOW; CK_LOW; CK_HIGH; CK_HIGH;
    CK_LOW; CK_HIGH;
    SPISW_Write(dat);
    CS_HIGH;
}
